package com.ktwlsoft.archivemanage.domain.business.businessService;

import com.alibaba.fastjson.JSONObject;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.sms.SmsService;
import com.ktwlsoft.archivemanage.domain.dao.entity.sms.SendSms;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.service.utils.RedisUtil;
import com.ktwlsoft.archivemanage.service.utils.VerificationCodeUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码
 *
 * @author Name on 2022/2/25 10:09
 * @version 1.0
 */
@Component
public class VerificationCodeService {

    /**
     * 日志对象
     **/
    private static Logger logger = LoggerFactory.getLogger(VerificationCodeService.class);

    /**
     * redis工具
     */
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 发送短信
     */
    @Autowired
    private SmsService smsService;

    /**
     * 获取手机验证码 on 2019/5/17 11:25
     *
     * @return ResponseEntity<Object>
     */
    public ResponseEntity<?> getVerificationCode(String phone,String id) {
        if (phone == null || "".equals(phone.trim())) {
            return ResponseEntity.ok(Result.body(null, ResultType.CHECK_ERROR).withMessage("手机号不能为空"));
        }
        if (id == null || "".equals(id.trim())) {
            return ResponseEntity.ok(Result.body(null, ResultType.CHECK_ERROR).withMessage("用户id不能为空"));
        }
        //获取验证码
        String s = VerificationCodeUtil.getRandomString();
        try {
            //存入redis
            redisUtil.set(id, s, 300);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResponseEntity.ok(Result.body(null, ResultType.SAVING_ERROR).withMessage("Redis服务出现错误"));
        }
        //发送短信
        SendSms sendSms = new SendSms();
        //短信渠道
        sendSms.setSmsChannel("1");
        //短信模板编码
        sendSms.setSmsTemplateEncoded("sendVerificationCode");
        //待发送手机号
        String[] strings = new String[]{phone};
        sendSms.setPhoneNumbers(strings);
        //短信模板变量
        Map<String, String> map = new HashMap<String, String>();
        map.put("verifycode", s);
        sendSms.setParamMap(map);
        return ResponseEntity.ok(smsService.sendSms(sendSms));
    }

    /**
     * 获取验证码图片 on 2020/4/8 12:08
     *
     * @param response response
     * @param request  request
     */
    public void getVerificationCode(HttpServletResponse response, HttpServletRequest request, @RequestParam Long id) {
        int width = 200;
        int height = 69;
        //生成对应宽高的初始图片
        BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //生成验证码字符并加上噪点，干扰线，返回值为验证码字符
        String randomText = VerificationCodeUtil.drawRandomText(width, height, verifyImg);
        try {
            //存入redis
            redisUtil.set(id.toString(), randomText, 300);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        //设置响应内容类型为图片
        response.setContentType("image/png");
        OutputStream os = null;
        try {
            //获取文件输出流
            os = response.getOutputStream();
            //输出图片流
            ImageIO.write(verifyImg, "png", os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    //关闭流
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 检查验证码 on 2019/5/17 11:25
     *
     * @return ResponseEntity<Object>
     */
    public ResponseEntity<Object> inspectVerificationCode(@ApiParam(value = "验证码", name = "code") @RequestParam(defaultValue = "") String code,
                                                          @ApiParam(value = "标识", name = "id") @RequestParam(defaultValue = "") String id) {
        if (code == null || "".equals(code.trim())) {
            return ResponseEntity.ok(Result.body(false, ResultType.CHECK_ERROR).withMessage("验证码为空"));
        }
        JSONObject object = getCode(id);
        if (!object.getBoolean("state")) {
            return ResponseEntity.ok(Result.body(false, ResultType.CHECK_ERROR).withMessage(object.getString("message")));
        }
        if (object.getString("data").toLowerCase().equals(code.toLowerCase())) {
            //删除验证码
            deleteCode(id);
            return ResponseEntity.ok(Result.body(true, ResultType.BUSINESS_SUCCESS).withMessage("验证码验证成功"));
        } else {
            return ResponseEntity.ok(Result.body(false, ResultType.BUSINESS_ERROR).withMessage("验证码不正确"));
        }
    }

    /**
     * 检查验证码 on 2019/5/17 11:25
     *
     * @return ResponseEntity<Object>
     */
    public boolean inspectVerification(String code,String id){
        if (code == null || "".equals(code.trim())) {
            return false;
        }
        JSONObject object = getCode(id);
        if (!object.getBoolean("state")) {
            return false;
        }
        if (object.getString("data").toLowerCase().equals(code.toLowerCase())) {
            //删除验证码
            deleteCode(id);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 从redis获取验证码 on 2019/5/17 16:32
     *
     * @param userId userId
     * @return JSONObject
     */
    private JSONObject getCode(String userId) {
        JSONObject object = new JSONObject();
        String s = "";
        try {
            Object o = redisUtil.get(userId);
            if (o == null) {
                object.put("state", false);
                object.put("message", "验证码已超时");
                return object;
            }
            s = o.toString();
        } catch (Exception e) {
            logger.error(e.getMessage());
            object.put("state", false);
            object.put("message", "Redis服务出现错误");
            return object;
        }
        object.put("state", true);
        object.put("data", s);
        return object;
    }

    private boolean deleteCode(String userId) {
        try {
            redisUtil.delete(userId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }
}